<template>
  <div ref="chartContainer" :style="{ width: '100%', height: props.height }"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, reactive } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  title: {
    type: String,
    default: 'SCM 数据统计'
  },
  // 新增xAxis数据属性
  xAxisData: {
    type: Array,
    default: () => ['项目A', '项目B', '项目C', '项目D', '项目E']
  },
  // 新增series数据属性
  seriesData: {
    type: Array,
    default: () => [10, 20, 15, 25, 18]
  },
  // 新增高度属性
  height: {
    type: String,
    default: '400px'
  }
})

const data = reactive({
  input: {
    projectId: props.title,
  }
});

const chartContainer = ref(null)
let chartInstance = null

// 初始化图表
const initChart = () => {
  if (chartContainer.value) {
    chartInstance = echarts.init(chartContainer.value)
    renderChart()
  }
}

// 渲染图表数据
const renderChart = () => {
  if (!chartInstance) return

  const option = {
    title: {
      text: props.title
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['数量']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: props.xAxisData
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '数量',
        type: 'bar',
        data: props.seriesData
      }
    ]
  }

  chartInstance.setOption(option)
}

// 响应式处理
const resizeChart = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 监听窗口大小变化
let resizeObserver = null
const observeResize = () => {
  if (chartContainer.value) {
    resizeObserver = new ResizeObserver(resizeChart)
    resizeObserver.observe(chartContainer.value)
  }
}

onMounted(() => {
  initChart()
  observeResize()
})

onBeforeUnmount(() => {
  if (resizeObserver) {
    resizeObserver.disconnect()
  }
  if (chartInstance) {
    chartInstance.dispose()
  }
})

// 监听title变化
watch(() => props.title, () => {
  renderChart()
})

// 监听xAxisData和seriesData变化
watch([() => props.xAxisData, () => props.seriesData], () => {
  renderChart()
})

</script>